package com.warmlight.voicepacket.ui.user.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.squareup.otto.Subscribe;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.comm.FocusAdapter;
import com.warmlight.voicepacket.bean.comm.CommBean;
import com.warmlight.voicepacket.bean.comm.CommList;
import com.warmlight.voicepacket.contract.CommContract;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.data.eventbus.MyCommunityLikeReply;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.loadmore.HeaderAndFooterRecyclerViewAdapter;
import com.warmlight.voicepacket.network.MapComm;
import com.warmlight.voicepacket.ottoEvent.ORecommBean;
import com.warmlight.voicepacket.plugin.QmzbMediaManager;
import com.warmlight.voicepacket.plugin.QmzbVideoPlayer;
import com.warmlight.voicepacket.presenter.CommPresenter;
import com.warmlight.voicepacket.ui.communitylm.widget.CommunityShare;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.ui.user.usercenter.MyCommunityAdapter;
import com.warmlight.voicepacket.utils.Log;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 动态列表
 */
public class MyDynamicFragment  extends com.warmlight.voicepacket.base.BaseFragment implements  CommContract.View,FocusAdapter.FocusItemListener{

    CommContract.Presenter mPresenter;


    CommList commList;

//    @BindView(R.id.recycler_view)
//    LoadRecyclerView mRecyclerView;
//
//    @BindView(R.id.app_myAuto)
//    AutoSwipeRefreshLayout mAuto;

//    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;

//    @BindView(R.id.comment_rl)
    RecyclerView mRecyclerView;

//    @BindView(R.id.rl_login)
    RelativeLayout rl_login;

//    @BindView(R.id.bt_login)
    Button bt_login;

    LinearLayoutManager linearLayoutManager;

    MyCommunityAdapter focusAdapter;

    PlayHandler playHandler;

    int currentPosition=0;

    int likePosition;

    private int isLike;

    int likeCommPosition;

    private int isCommLike;

    int page;

    int pageSize=8;


    String mType;

    String typeClick;//点赞的类型

    private boolean liveVideo;

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    private TextView tv_no_community;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        View view = inflater.inflate(R.layout.fragment_video_my,container,false);

        return view;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews(view);
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @org.greenrobot.eventbus.Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxx(MyCommunityLikeReply myCommunityLikeReply){
        if (myCommunityLikeReply.getType() == 0){
            String parentId = myCommunityLikeReply.getParentId();
            int msgType = myCommunityLikeReply.getMsgType();
            for (int i=0;i<focusAdapter.getItemCount();i++){
                if (TextUtils.equals(parentId,focusAdapter.getData().get(i).getId())){
                    if (msgType == 0){
                        if(focusAdapter.getData().get(i).getIs_like()==1){
                            focusAdapter.getData().get(i).setIs_like(0);
                            String like_num = focusAdapter.getData().get(i).getLike_num();
                            if (like_num.contains("k") || like_num.contains("w")){

                            }else{
                                focusAdapter.getData().get(i).setLike_num((Integer.valueOf(like_num)-1)+"");
                            }

                        }else{
                            focusAdapter.getData().get(i).setIs_like(1);
                            String like_num = focusAdapter.getData().get(i).getLike_num();
                            if (like_num.contains("k") || like_num.contains("w")){

                            }else{
                                focusAdapter.getData().get(i).setLike_num((Integer.valueOf(like_num)+1)+"");
                            }

                        }

                    }else if (msgType == 1){

                        String comment_num = focusAdapter.getData().get(i).getComment_num();
                        if (comment_num.contains("k") || comment_num.contains("w")){

                        }else{
                            focusAdapter.getData().get(i).setComment_num((Integer.valueOf(comment_num)+1)+"");
                        }
                    }
                    focusAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    // 接受事件
    @Subscribe
    public void setContent(ORecommBean data) {
        smartRefreshLayout.autoRefresh();
//        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMREFRESH));
    }

    @org.greenrobot.eventbus.Subscribe(threadMode = ThreadMode.MAIN)
    public void xxx(Login login){
//        initData();

        isLogin();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            playMedia();
        }else{
            stopVideo();
        }
    }



    public void initViews(View view) {

        smartRefreshLayout = view.findViewById(R.id.refreshLayout);
        mRecyclerView = view.findViewById(R.id.comment_rl);
        rl_login = view.findViewById(R.id.rl_login);
        bt_login = view.findViewById(R.id.bt_login);
        tv_no_community = view.findViewById(R.id.tv_no_community);

        playHandler=new PlayHandler();
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                setData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                setData(true);
            }
        });
        focusAdapter = new MyCommunityAdapter(getActivity(),this,"",1);
//        mRecyclerView.setIsHaveData(false);

        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

        //自定义加载布局
        HeaderAndFooterRecyclerViewAdapter customAdapter = new HeaderAndFooterRecyclerViewAdapter(focusAdapter);

        mRecyclerView.setAdapter(customAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        playVideo();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void initData() {
        isPrepared = true;
        lazyLoad();
    }



//    /**
//     * 懒加载
//     */
    protected void lazyLoad() {
//        if (!isPrepared || !isVisible) {
//            return;
//        }
        isPrepared = false;
//        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMREFRESH));

        isLogin();

    }

    private void isLogin() {
        if (SPUtils.isLogined()){
            smartRefreshLayout.setVisibility(View.VISIBLE);
            rl_login.setVisibility(View.GONE);
            setData(true);
        }else{
            smartRefreshLayout.setVisibility(View.GONE);
            rl_login.setVisibility(View.VISIBLE);
            bt_login.setVisibility(View.VISIBLE);
            bt_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    MobclickAgent.onEvent(getContext(), MobClickHelper.PROFILE_STATUS_LOGIN);

                    Intent intent = new Intent(getContext(), LoginRegistActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    public void setData(final boolean isRefresh){

        if (isRefresh){
            page = 1;
        }else{
            page ++;
        }

        String url = HttpConfig.USER_POST;

        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("page",String.valueOf(page));
        treeMap.put("pagesize",String.valueOf(pageSize));

        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            String data = responseData.getData();
                            CommBean list = new Gson().fromJson(data, CommBean.class);
                            if (isRefresh){
                                focusAdapter.setData(list.getList());
                                if (list.getList().size() == 0){
                                    smartRefreshLayout.setNoMoreData(true);
                                    rl_login.setVisibility(View.VISIBLE);
                                    bt_login.setVisibility(View.GONE);
                                    tv_no_community.setVisibility(View.VISIBLE);
                                    tv_no_community.setText("还未发布动态奥~");
                                }else{
                                    rl_login.setVisibility(View.GONE);
                                }
//                                playMedia();
                            }else {
                                focusAdapter.addData(list.getList());
                                if (list.getList().size() == 0){
                                    smartRefreshLayout.setNoMoreData(true);
                                }
                            }
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public CommContract.Presenter getPresenter() {
        if (mPresenter==null){
            mPresenter=new CommPresenter(this,getActivity());
        }
        return mPresenter;
    }

    @Override
    public void setPresenter(CommContract.Presenter presenter) {

    }

    @Override
    public void onRecommList(CommBean list) {
//        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMSTOP));

//        mRecyclerView.setIsHaveData(false);
//        mAuto.setRefreshing(false);
        if (page == 1){
            focusAdapter.setData(list.getList());
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
//            playMedia();
        }else {
            focusAdapter.addData(list.getList());
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
        }
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();

//        mData.addAll(list.getList());
//        if (type==0){
//            focusAdapter.setData(list.getList());
//            if (mData.get(0).getVideo() !=null)
//            playMedia();
//        }else if (type==1){
//            focusAdapter.addData(list.getList());
//        }

    }

    private void playMedia(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=0;
                playHandler.handleMessage(message);
            }
        },200);
    }


    /**
     * 播放视频
     */
    private void playVideo(){

        if (currentPosition == playVideoss()){
            return;
        }

        playVideo(playVideoss());

    }


    /**
     * 滑动或者holder是图片暂停播放
     */
    public void stopVideo(){
        try {
            if (liveVideo)
                QmzbMediaManager.pause();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 播放视频
     */
    private void playVideo(int firstPosition) {

        Log.e("可见区域最大值"+firstPosition);

        currentPosition = firstPosition;

        //视频页
        if (focusAdapter.getData().size() > currentPosition && focusAdapter.getData().size() != 0)
            commList = focusAdapter.getData().get(currentPosition);
        View childAt = linearLayoutManager.findViewByPosition(currentPosition);

        if (childAt !=null)

            if (commList.getPics().size()==0){
                liveVideo=true;
                focusAdapter.videoPreppare(childAt,currentPosition);

            }else{

                if (commList.getPics().size()>0){
                    if (currentPosition==0){
                        return;
                    }
                    stopVideo();
                }
            }
    }


    private class PlayHandler extends Handler{

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    playVideo(0);
                    break;
            }
        }
    }


    @Override
    public void isLikeClick(int position,String type,String clickType) {
        typeClick=clickType;
        likePosition=position;
        mType=type;
        isLike=focusAdapter.getData().get(position).getIs_like();
        int count= isLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",focusAdapter.getData().get(position).getId());
        mapComm.put("type","1");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

    }

    @Override
    public void isLikeCommClick(int position, String type,String clickType) {
        typeClick=clickType;
        likeCommPosition=position;
        mType=type;
        isCommLike=focusAdapter.getData().get(position).getGod_info().getIs_like();
        int count= isCommLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",focusAdapter.getData().get(position).getGod_info().getId());
        mapComm.put("type","2");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

    }

    @Override
    public void onLikeList(String list) {

        if (list.toString().equals("成功")){

            if (typeClick.equals("comm")){
                commLike();
                return;
            }

            commList = focusAdapter.getData().get(likePosition);

            isLike=isLike==0 ? 1 : 0;

            int count= isLike==0 ? -1 : 1;

//            mData.get(likePosition).setIs_like(isLike);
            String like_num = focusAdapter.getData().get(likePosition).getLike_num();
            if (!like_num.contains("k") && !like_num.contains("w")) {
                int resetCount = Integer.valueOf(focusAdapter.getData().get(likePosition).getLike_num());

                focusAdapter.getData().get(likePosition).setLike_num(String.valueOf(resetCount + count));
            }

            focusAdapter.getData().get(likePosition).setIs_like(isLike);
            focusAdapter.isLike(likePosition);
        }

    }

    /**
     * 神评点赞
     */
    private void commLike(){
        commList = focusAdapter.getData().get(likeCommPosition);

        isCommLike=isCommLike==0 ? 1 : 0;

        int count= isCommLike==0 ? -1 : 1;

//        mData.get(likeCommPosition).getGod_info().setIs_like(isCommLike);
        String likenum = focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num();
        if (!likenum.contains("k") && !likenum.contains("w")) {
            int resetCount = Integer.valueOf(focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num());

            focusAdapter.getData().get(likeCommPosition).getGod_info().setLike_num(String.valueOf(resetCount + count));
        }

        focusAdapter.getData().get(likeCommPosition).getGod_info().setIs_like(isCommLike);
        focusAdapter.isLike(likeCommPosition);
    }


    /**
     * 获取当前viewke可见的索引
     * @return
     */
    public int playVideoss() {
        int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        int currentIndex = firstVisibleItem;
        int lastHeight = 0;
        for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
            View view = linearLayoutManager.getChildAt(i - firstVisibleItem);
            if (null == view) {
                continue;
            }
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            Rect localRect = new Rect();
            view.getLocalVisibleRect(localRect);
            int showHeight = localRect.bottom - localRect.top;
            if (showHeight > lastHeight) {
                currentIndex = i;
                if (currentIndex < 0) {
                    currentIndex = 0;
                }
                lastHeight = showHeight;
            }
        }
        return currentIndex;
    }

    @Override
    public void shareClick(final int position) {
        Map<String,String> map=new HashMap<>();
        map.put("title",focusAdapter.getData().get(position).getShare().getTitle());
        map.put("msc",focusAdapter.getData().get(position).getShare().getDesc());
        map.put("url",focusAdapter.getData().get(position).getShare().getH5_url());
        map.put("img",focusAdapter.getData().get(position).getShare().getPic_url());
        map.put("type","1");
        map.put("id",focusAdapter.getData().get(position).getId());
        map.put("is_mine","1");
        CommunityShare instance = CommunityShare.getInstance(map);
        instance.setOnDelete(new CommunityShare.OnDelete() {
            @Override
            public void onDelete() {
                stopVideo();
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("是否删除该动态")
                        .setCancelable(true)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                delete(focusAdapter.getData().get(position).getId(),position);
                                dialog.dismiss();
                            }
                        }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
        instance.show(getChildFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE),"ads");
    }

    private void delete(String id, final int position) {

        String url = HttpConfig.DEL_USER_POST;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("id",id);
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            focusAdapter.removeItem(position);
                            EventBus.getDefault().post(new NotifyMyPlaylist("net"));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort(getContext(),"请求失败，请重试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void onRecommFailure() {
//        mAuto.setRefreshing(false);
        smartRefreshLayout.autoRefresh();
    }

    @Override
    public void onRecommNoMore() {

    }

    @Override
    public void onNoNetWork() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()){
            playMedia();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            QmzbVideoPlayer.onPlayOnPause();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
